package com.iqiao.platform.controller.admin;

import com.github.pagehelper.PageInfo;
import com.iqiao.common.exception.ResetException;
import com.iqiao.common.web.Servlets;
import com.iqiao.common.web.result.JsonResult;
import com.iqiao.common.web.result.PageResult;
import com.iqiao.common.web.result.ReturnCode;
import com.iqiao.platform.model.Admin;
import com.iqiao.platform.service.AdminService;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by flt on 2017/11/13.
 */
@RestController
@RequestMapping(value = "admins")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     *  查询管理员列表
     * @param request
     * @param response
     * @return
     */
    @GetMapping()
    public JsonResult findList(
            HttpServletRequest request,
            HttpServletResponse response) {
        Map<String, Object> params = Servlets.getParams(request);
        PageInfo<Admin> pageInfo = adminService.findPage(params);
        return PageResult.success(pageInfo);
    }

    @PostMapping()
    public JsonResult save(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody Map<String, Object> map) {
        String nikename = MapUtils.getString(map, "nikename");
        String username = MapUtils.getString(map, "username");
        String password = MapUtils.getString(map, "password");
        Long roleId = MapUtils.getLong(map, "roleId");

        if (StringUtils.isBlank(nikename)) {
            throw new ResetException(ReturnCode.ADMIN_NIKENAME_NOT_NULL, "昵称不能为空！");
        }
        if (StringUtils.isBlank(username)) {
            throw new ResetException(ReturnCode.ADMIN_USERNAME_NOT_NULL, "用户名不能为空！");
        }
        if (StringUtils.isBlank(password)) {
            throw new ResetException(ReturnCode.ADMIN_PASSWORD_NOT_NULL, "密码不能为空！");
        }
        if (null == roleId) {
            throw new ResetException(ReturnCode.ADMIN_ROLE_NOT_NULL, "角色不能为空！");
        }

        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setNikename(nikename);
        admin.setPassword(password);
        admin.setRoleId(roleId);
        Long id = adminService.save(admin);
        Map<String, Object> doMap = new HashMap<>();
        doMap.put("id", id);
        return JsonResult.success(doMap, "管理员信息保存成功！");
    }

}
